# coding=utf-8
import tkinter
from tkinter import *
from tkinter import filedialog
import threading
import sys
import queue
import signature
import shutil


# 自定义re_Text,用于将stdout映射到Queue
class re_text:

    def __init__(self, queue0):
        self.queue = queue0

    def write(self, content):
        self.queue.put(content)


def ass_how(ap=0, key_int='', key_pwd=''):
    if ap == 2:
        if key_int != '':
            if key_pwd != '':
                f_path1 = filedialog.askopenfilename(filetypes=[("hap文件", "*hap")])
                if f_path1 != '':
                    f_path1 = str.replace(f_path1, '\\', '/')
                    #shutil.copy(f_path, './iut/a1.hap')
                    f_path2 = filedialog.askopenfilename(filetypes=[("cer文件", "*cer")])
                    if f_path2 != '':
                        f_path2 = str.replace(f_path2, '\\', '/')
                        #shutil.copy(f_path, './iut/a1.cer')
                        f_path3 = filedialog.askopenfilename(filetypes=[("p12文件", "*p12")])
                        if f_path3 != '':
                            f_path3 = str.replace(f_path3, '\\', '/')
                            #shutil.copy(f_path, './iut/a1.p12')
                            f_path4 = filedialog.askopenfilename(filetypes=[("p7b文件", "*p7b")])
                            if f_path4 != '':
                                f_path4 = str.replace(f_path4, '\\', '/')
                                #shutil.copy(f_path, './iut/a1.p7b')
                                info = signature.hap_ap(f_path1, f_path4, f_path2, f_path3,
                                                        key_int, key_pwd, key_pwd)
                                print(info)
                                info = signature.hap_install(1, './out/app1-signed.hap')
                                print(info)
            else:
                print('请输入密码！')
        else:
            print('请输入密钥！')
    else:
        if ap == 4:
            if key_int != '':
                if key_pwd != '':
                    f_path = filedialog.askopenfilename(filetypes=[("hap文件", "*hap")])
                    if f_path != '':
                        f_path = str.replace(f_path, '\\', '/')
                        #shutil.copy(f_path, './iut/a1.hap')
                        ifo = signature.add_key(key_int, key_pwd)
                        print(ifo)
                        ifo = signature.cer_ap('', './lib/OpenHarmony.p12', key_int, key_pwd)
                        print(ifo)
                        info = signature.p7b_ap(f_path)
                        print(info)
                        info = signature.hap_ap(f_path, './out/app1-profile.p7b',
                                                './out/z1.cer',
                                                './lib/OpenHarmony.p12',
                                                key_int, key_pwd)
                        print(info)
                        info = signature.hap_install(0, './out/app1-signed.hap')
                        print(info)
                else:
                    print('请输入密码！')
            else:
                print('请输入密钥！')
        else:
            if ap == 5:
                signature.hdc_device()
            else:
                f_path = filedialog.askopenfilename(filetypes=[("hap文件", "*hap")])
                if f_path != '':
                    f_path = str.replace(f_path, '\\', '/')
                    if ap == 0:
                        shutil.copy(f_path, './iut/a1.hap')
                        info = signature.hap_install(0, './iut/a1.hap')
                        print(info)
                    if ap == 3:
                        shutil.copy(f_path, './iut/a1.hap')
                        info = signature.hap_install(1, './iut/a1.hap')
                        print(info)
                    if ap == 1:
                        info = signature.cer_ap()
                        print(info)
                        info = signature.p7b_ap(f_path)
                        print(info)
                        info = signature.hap_ap(f_path)
                        print(info)
                        info = signature.hap_install(0, './out/app1-signed.hap')
                        print(info)


def hap_install():
    t = threading.Thread(target=ass_how, args=(0, ''))
    t.start()


def hap_signature():
    t = threading.Thread(target=ass_how, args=(1, ''))
    t.start()


def hos_hap_signature(in_key, key_pwd):
    t = threading.Thread(target=ass_how, args=(2, in_key, key_pwd))
    t.start()


def hos_hap_install():
    t = threading.Thread(target=ass_how, args=(3, ''))
    t.start()


def add_key(in_key, key_pwd):
    t = threading.Thread(target=ass_how, args=(4, in_key, key_pwd))
    t.start()


def lis_Device():
    t = threading.Thread(target=ass_how, args=(5, ''))
    t.start()


class GUI:

    def __init__(self, root0):
        # new 一个Queue用于保存输出内容
        self.key = tkinter.StringVar()
        self.pwd = tkinter.StringVar()
        self.label = None
        self.entry = None
        self.text = None
        self.scrollBar = None
        self.button = None
        self.root = None
        self.msg_queue = queue.Queue()
        self.initGUI(root0)

    # 在show_msg方法里，从Queue取出元素，输出到Text
    def show_msg(self):
        while not self.msg_queue.empty():
            content = self.msg_queue.get()
            self.text.insert(END, content)
            self.text.see(END)

        # after方法再次调用show_msg
        self.root.after(100, self.show_msg)

    def initGUI(self, root1):
        self.root = root1
        self.root.title("open Harmony一键签名工具")
        self.root.geometry("635x390+520+300")
        self.root.resizable(width=False, height=False)
        self.button = Button(self.root, text="openharmony一键签名安装", command=hap_signature, width='90')
        self.button.grid(row=0, columnspan=2, sticky="w")
        self.button = Button(self.root, text="openharmony一键安装", command=hap_install, width='90')
        self.button.grid(row=1, columnspan=2, sticky="w")
        self.button = Button(self.root, text="harmonyos一键安装", command=hos_hap_install, width='90')
        self.button.grid(row=2, columnspan=2, sticky="w")
        self.button = Button(self.root, text="openharmony自定义密钥并签名安装", command=self.key_int_add, width='44')
        self.button.grid(row=3, column=0, sticky="w", columnspan=2)
        self.button = Button(self.root, text="harmonyos签名安装，会弹出4次文件选择框",
                             command=self.key_int, width='44')
        self.button.grid(row=3, column=1, sticky="e", columnspan=1)
        self.button = Button(self.root, text="生成DevEco Studio可用的cer文件和p7b文件", command='', width='90')
        self.button.grid(row=4, columnspan=2, sticky="w")
        self.button = Button(self.root, text="显示连接设备列表，建议先点一点再操作其它", command=lis_Device, width='90')
        self.button.grid(row=5, columnspan=2, sticky="w")
        self.label = Label(self.root, text="密钥名：")
        self.label.grid(row=6, sticky="w")
        self.label = Label(self.root, text="密码：")
        self.label.grid(row=7, sticky="w")
        self.entry = Entry(self.root, width=80, textvariable=self.key)
        self.entry.grid(row=6, column=1, columnspan=1, sticky="w")
        self.entry = Entry(self.root, width=80, show='*', textvariable=self.pwd)
        self.entry.grid(row=7, column=1, columnspan=1, sticky="w")
        self.text = Text(self.root, height=12, width=90, )
        self.text.grid(row=8, sticky="w", columnspan=2)
        # 启动after方法
        self.root.after(100, self.show_msg)

        # 将stdout映射到re_Text
        sys.stdout = re_text(self.msg_queue)
        #self.root.attributes('-topmost', 'true')

        root.mainloop()

    def key_int(self):
        in_key = self.key.get()
        in_pwd = self.pwd.get()
        hos_hap_signature(in_key, in_pwd)

    def key_int_add(self):
        in_key = self.key.get()
        in_pwd = self.pwd.get()
        add_key(in_key, in_pwd)


if __name__ == "__main__":
    root = Tk()
    GUI(root)
